package com.woniuxy.patrol.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.patrol.pojo.PatrolPointRecord;
import com.woniuxy.patrol.service.PatrolRecordService;
import com.woniuxy.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

/**
 * 巡更记录控制器（对应《巡更demo.docx》3.1.3及3.3.3巡更记录功能）
 */
@RestController
@RequestMapping("/patrol/record")
@Slf4j
public class PatrolRecordController {

    @Resource
    private PatrolRecordService recordService;

    @PostMapping("/submit")
    public ResponseUtil submitRecord(@RequestBody PatrolPointRecord record) {
        return recordService.submitRecord(record);
    }
    /**
     * 获取所有记录
     * @return
     */
    @GetMapping("/list")
    public ResponseUtil getAll() {
        return recordService.getAll();
    }

    @GetMapping("/byTask")
    public ResponseUtil getByTask(@RequestParam Long taskId) {
        return recordService.getByTaskId(taskId);
    }

    @GetMapping("/byPoint")
    public ResponseUtil getByPoint(@RequestParam Long pointId) {
        return recordService.getByPointId(pointId);
    }
    // 新增：按社区查询记录（支持分页和时间筛选）
    @GetMapping("/byCommunity")
    public ResponseUtil getByCommunity(
            @RequestParam Long communityId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 调用服务层方法（需要在Service和Mapper中实现）
        Page<PatrolPointRecord> page = recordService.getByCommunity(
                communityId, startTime, endTime, pageNum, pageSize);
        return ResponseUtil.success(page);
    }

    // 新增：导出记录接口
//    @GetMapping("/export")
//    public ResponseUtil exportByCommunity(
//            @RequestParam Long communityId,
//            @RequestParam(required = false) String startTime,
//            @RequestParam(required = false) String endTime) {
//        // 调用服务层导出方法（返回文件URL或文件流）
//        String fileUrl = recordService.exportByCommunity(communityId, startTime, endTime);
//        return ResponseUtil.success(fileUrl);
//    }
    // 巡更记录导出接口
//    @GetMapping("/export")
//    public void exportRecords(
//            @RequestParam Long communityId,
//            @RequestParam(required = false) String startTime,
//            @RequestParam(required = false) String endTime,
//            HttpServletResponse response) {
//        try {
//            // 设置响应头（关键：告诉浏览器这是Excel文件）
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//            String fileName = URLEncoder.encode("巡更记录_" + LocalDate.now() + ".xlsx", "UTF-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//
//            // 生成记录Excel并写入响应流
//            ByteArrayOutputStream outputStream = recordService.exportRecords(communityId, startTime, endTime);
//            outputStream.writeTo(response.getOutputStream());
//            outputStream.flush();
//            outputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//        }
//    }
    // 导出巡更记录接口
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportRecords(
            @RequestParam Long communityId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        try {
            // 调用服务生成Excel文件流
            ByteArrayOutputStream outputStream = recordService.exportRecords(communityId, startTime, endTime);

            // 设置响应头（关键：告诉浏览器这是文件下载）
            HttpHeaders headers = new HttpHeaders();
            String filename = "巡更记录_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx";
            headers.setContentDispositionFormData("attachment",
                    URLEncoder.encode(filename, StandardCharsets.UTF_8.name())); // 解决中文文件名乱码
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));

            // 返回文件流
            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    // 新增：统计数据接口（前端调用此接口获取统计信息）
    @GetMapping("/stats")
    public ResponseUtil getPatrolStats(@RequestParam Long communityId) {
        return recordService.getStats(communityId);
    }

    // 新增：最近异常记录接口（前端调用此接口获取异常列表）
    @GetMapping("/recentExceptions")
    public ResponseUtil getRecentExceptions(
            @RequestParam Long communityId,
            @RequestParam(defaultValue = "5") Integer limit) {
        return recordService.getRecentExceptions(communityId, limit);
    }
}